<template>
    <view>
        <!-- 商城订单确认页 -->
        <custom-navbar :showTitle="false" backgroundColor="#ffffff" textColor="#000000" :showBack="true"
            :isCoverNav="false"></custom-navbar>
        <view class="shopBook" :style="'height: calc(100vh - ' + navHeight + 'px);'">
            <!-- 收货信息表单 -->
            <view class="delivery-info">
                <view class="info-header">
                    <text class="header-title">收货信息</text>
                </view>
                <view class="info-form">
                    <view class="form-item">
                        <text class="form-label">姓名</text>
                        <input class="form-input" v-model="deliveryInfo.name" placeholder="请输入收货人姓名" />
                    </view>
                    <view class="form-item">
                        <text class="form-label">手机号</text>
                        <input class="form-input" v-model="deliveryInfo.phone" placeholder="请输入手机号" type="number" />
                    </view>
                </view>
            </view>
            
            <!-- 商品列表 -->
            <view class="product-section">
                <view class="section-header">
                    <text class="header-title">商品清单</text>
                </view>
                <view class="product-list">
                    <view class="product-item" v-for="(item, index) in cartItems" :key="index">
                        <view class="product-image">
                            <image :src="getImageUrl(item.image)" mode="aspectFill" class="item-image"></image>
                        </view>
                        <view class="product-info">
                            <view class="product-name">{{ item.title }}</view>
                            <view class="product-details">
                                <text class="product-quantity">数量：{{ item.num }}</text>
                                <text class="product-total">¥{{ (item.price * item.num).toFixed(2) }}</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            
            <!-- 底部确认按钮 -->
            <view class="footer-section">
                <view class="total-info">
                    <text class="total-label">总计：</text>
                    <text class="total-amount">¥{{ totalAmount }}</text>
                </view>
                <view class="confirm-btn">
                    <up-button color="rgba(57, 97, 54, 1)" round custom-class="btn" @tap.native="handleConfirm"
                        :loading="confirmLoading" :disabled="confirmLoading" loading-text="确认中...">
                        {{ confirmLoading ? '确认中...' : '确认订单' }}
                    </up-button>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted, computed } from 'vue'
import customNavbar from '../../components/custom-navbar/index.vue'
import { globalCart, type CartItem } from '@/composables/useCart'
import { cartListFun, orderGoodsCreateFun } from '@/api/port'

// 响应式数据
const navHeight = ref<number>(uni.getStorageSync('navHeight') ? uni.getStorageSync('navHeight') : 88)
const cartItems = ref<CartItem[]>([])
const confirmLoading = ref<boolean>(false)

// 收货信息
const deliveryInfo = ref({
    name: '',
    phone: ''
})

// 计算总金额
const totalAmount = computed(() => {
    return cartItems.value.reduce((total, item) => {
        return total + (item.price * item.num)
    }, 0).toFixed(2)
})

// 页面加载时获取购物车数据
onLoad((options) => {
    loadCartData(options)
})

/**
 * 加载购物车数据
 * @param options 页面参数
 */
const loadCartData = async (options: any): void => {
    try {
        // 调用cartListFun接口获取购物车数据
        const result = await cartListFun()
        
        if (result.code === 1 && result.data) {
            // 将接口返回的数据转换为CartItem格式
            cartItems.value = result.data.map((item: any) => ({
                id: item.id || item.product_id,
                title: item.title || item.name,
                price: parseFloat(item.price) || 0,
                num: parseInt(item.num) || 1,
                image: item.image || item.cover,
                desc: item.desc || item.description || ''
            }))
        } else {
            cartItems.value = []
        }
        
        if (cartItems.value.length === 0) {
            uni.showToast({
                title: '购物车为空',
                icon: 'error',
                duration: 2000
            })
            setTimeout(() => {
                uni.navigateBack()
            }, 2000)
            return
        }
        
        console.log('购物车商品:', cartItems.value)
        console.log('总金额:', totalAmount.value)
    } catch (error) {
        console.error('加载购物车数据失败:', error)
        uni.showToast({
            title: '获取购物车数据失败',
            icon: 'error'
        })
        setTimeout(() => {
            uni.navigateBack()
        }, 2000)
    }
}

/**
 * 获取图片URL，处理可能的逗号分隔字符串
 * @param image 图片字段，可能是字符串或逗号分隔的字符串
 * @returns 图片URL
 */
const getImageUrl = (image: string): string => {
    if (!image) return ''
    // 如果是逗号分隔的字符串，取第一个
    return image.split(',')[0].trim()
}

/**
 * 确认订单
 */
const handleConfirm = async (): void => {
    // 验证收货信息
    if (!deliveryInfo.value.name.trim()) {
        uni.showToast({
            title: '请输入收货人姓名',
            icon: 'error'
        })
        return
    }
    
    if (!deliveryInfo.value.phone.trim()) {
        uni.showToast({
            title: '请输入手机号',
            icon: 'error'
        })
        return
    }
    
    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(deliveryInfo.value.phone)) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'error'
        })
        return
    }
    
    try {
        confirmLoading.value = true
        
        // 构建订单数据
        const orderData = {
            name: deliveryInfo.value.name,
            phone: deliveryInfo.value.phone,
            cart_ids: cartItems.value.map(item => item.id).join(','),
            // totalAmount: totalAmount.value
        }
        const res = await orderGoodsCreateFun(orderData)
        if (res.code === 1) {
            uni.showToast({
                title: '订单创建成功',
                icon: 'success',
                duration: 2000
            })
            setTimeout(() => {
                uni.navigateTo({
                    url: `/subpackage/shopPayPage/shopPayPage?orderId=${res.data.id}&totalAmount=${totalAmount.value}`
                })
            }, 1000)
        } else {
            uni.showToast({
                title: res.msg,
                icon: 'error',
                duration: 2000
            })
        }
        
        
    } catch (error) {
        console.error('确认订单失败:', error)
        uni.showToast({
            title: '确认订单失败',
            icon: 'error'
        })
    } finally {
        confirmLoading.value = false
    }
}
</script>

<style scoped>
.shopBook {
    background-color: #f5f5f5;
    padding: 0;
    overflow-y: auto;
}

/* 收货信息样式 */
.delivery-info {
    background-color: #ffffff;
    margin: 20rpx;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.info-header {
    margin-bottom: 30rpx;
}

.header-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
}

.info-form {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
}

.form-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
}

.form-item:last-child {
    border-bottom: none;
}

.form-label {
    font-size: 28rpx;
    color: #333333;
    width: 120rpx;
    flex-shrink: 0;
}

.form-input {
    flex: 1;
    font-size: 28rpx;
    color: #333333;
    padding: 0 20rpx;
    height: 60rpx;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    border: none;
}

/* 商品列表样式 */
.product-section {
    background-color: #ffffff;
    margin: 20rpx;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.section-header {
    margin-bottom: 30rpx;
}

.product-list {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
}

.product-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
}

.product-item:last-child {
    border-bottom: none;
}

.product-image {
    width: 120rpx;
    height: 120rpx;
    margin-right: 24rpx;
    flex-shrink: 0;
}

.item-image {
    width: 100%;
    height: 100%;
    border-radius: 12rpx;
    object-fit: cover;
}

.product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12rpx;
}

.product-name {
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
    line-height: 1.4;
}

.product-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.product-quantity {
    font-size: 24rpx;
    color: #666666;
}

.product-total {
    font-size: 28rpx;
    color: #ff6b35;
    font-weight: bold;
}

/* 底部样式 */
.footer-section {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    padding: 30rpx;
    border-top: 1rpx solid #f0f0f0;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.total-info {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20rpx;
    gap: 10rpx;
}

.total-label {
    font-size: 28rpx;
    color: #333333;
}

.total-amount {
    font-size: 36rpx;
    color: #ff6b35;
    font-weight: bold;
}

.confirm-btn {
    width: 100%;
}

.confirm-btn .btn {
    width: 100%;
    height: 88rpx;
    font-size: 32rpx;
    font-weight: bold;
}

/* 为底部按钮预留空间 */
.shopBook {
    padding-bottom: 200rpx;
}
</style>
